var $ = window.$;
var event = require('./event');

/**
 * 接受键盘输入, 转发给event center
 * 由于是集中分发,所以部分模块监听同一个按键, 并不保证先后顺序
 * 解决方法时, 涉及冲突的模块, 自行标记一个focus变量, 在模块内发生任意操作时, 触发focus
 * focus时, 再处理冲突按键
 * 一个模块获得focus时,通知其他模块blur
 * */
var _inited = false;

var ret = {
	init: function(){
		if(_inited){
			return;
		}
		var self = this;
		this.keyStatus = {};
		$(window.document.body).keydown(function(e){
			self.shift = e.shiftKey;
			self.ctrl = e.ctrlKey;
			self.alt = e.altKey;
			if(!self.keyStatus[e.which]){
				event.trigger(event.events.key.down, self.getEvent(e));
				self.keyStatus[e.which] = true;
			}else{
				event.trigger(event.events.key.repeat, self.getEvent(e));
			}
		}).keyup(function(e){
			self.shift = e.shiftKey;
			self.ctrl = e.ctrlKey;
			self.alt = e.altKey;
			if(self.keyStatus[e.which]){
				event.trigger(event.events.key.up, self.getEvent(e));
				self.keyStatus[e.which] = false;
			}
			
		});
		_inited = true;
	},

	isShift: function(){
		return this.shift;
	},

	isCtrl: function () {
		return this.ctrl;
	},

	isAlt: function () {
		return this.alt;
	},

	isCommand: function() {
		return this.com;
	},

	releaseKey: function(){
		for(var key in this.keyStatus){
			if(!this.keyStatus.hasOwnProperty(key)){
				continue;
			}
			if(this.keyStatus[key]){
				event.trigger(event.events.key.up, {key: key});
			}
		}
		this.keyStatus = {};
	},

	getEvent: function(e){
		return {
			key: e.which,
			ctrl: e.ctrlKey,
			alt: e.altKey,
			shift: e.shiftKey
		}
	}
};

module.exports = ret;